﻿using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Web.Routing;
using BrnMall.Core;
using BrnMall.Services;
using BrnMall.Web.Framework;
using BrnMall.Web.StoreAdmin.Models;
using BrnMall.Manager.Domain.Store;
using BrnMall.Manager.Manager.Store;
using Newtonsoft.Json;
using BrnMall.Sdk.QQMap;
using BrnMall.CacheManager;

namespace BrnMall.Web.StoreAdmin.Controllers
{
    /// <summary>
    /// 店铺后台店铺控制器类
    /// </summary>
    public partial class StoreController : BaseStoreAdminController
    {
        /// <summary>
        /// 编辑店铺
        /// </summary>
        [HttpGet]
        public ActionResult EditStore()
        {
            StoreModel model = new StoreModel();

            model.StoreName = WorkContext.StoreInfo.Name;
            model.RegionId = WorkContext.StoreInfo.RegionId;
            model.StoreIid = WorkContext.StoreInfo.StoreIid;
            model.Logo = WorkContext.StoreInfo.Logo;
            model.WeApp_Qrcode = WorkContext.StoreInfo.WeApp_Qrcode;
            model.WeService_Qrcode = WorkContext.StoreInfo.WeService_Qrcode;
            model.Email = WorkContext.StoreInfo.Email;
            model.WebSite = WorkContext.StoreInfo.WebSite;
            model.Mobile = WorkContext.StoreInfo.Mobile;
            model.Phone = WorkContext.StoreInfo.Phone;
            model.QQ = WorkContext.StoreInfo.QQ;
            model.WW = WorkContext.StoreInfo.WW;
            model.Theme = WorkContext.StoreInfo.Theme;
            model.Banner = WorkContext.StoreInfo.Banner;
            model.Announcement = WorkContext.StoreInfo.Announcement;
            model.Description = WorkContext.StoreInfo.Description;
            model.Address = WorkContext.StoreInfo.Address;
            model.Fax = WorkContext.StoreInfo.Fax;
            model.Location = WorkContext.StoreInfo.Location;
            model.VideoSrc = WorkContext.StoreInfo.VideoSrc;
            model.SupportPhone = WorkContext.StoreInfo.SupportPhone;
            model.SupportCompany = WorkContext.StoreInfo.SupportCompany;
            model.StorePid = WorkContext.StoreInfo.StorePid;
            LoadStore(model.RegionId);
            return View(model);
        }

        /// <summary>
        /// 编辑店铺
        /// </summary>
        [HttpPost]
        public ActionResult EditStore(StoreModel model)
        {
            int storeId = Stores.GetStoreIdByName(model.StoreName);
            if (storeId > 0 && storeId != WorkContext.StoreId)
                ModelState.AddModelError("StoreName", "店铺名已经存在");

            if (!string.IsNullOrEmpty(model.WebSite))
            {
                var _storeId = StoreInfoManager.GetStoreIdByWebSite(model.WebSite);
                if (_storeId > 0 && _storeId != WorkContext.StoreId)
                    ModelState.AddModelError("StoreName", "小程序网站域名已被别人使用");
            }
                

            if (ModelState.IsValid)
            {
                WorkContext.StoreInfo.Name = model.StoreName;
                WorkContext.StoreInfo.RegionId = model.RegionId;
                WorkContext.StoreInfo.StoreIid = model.StoreIid;
                WorkContext.StoreInfo.Logo = model.Logo ?? "";
                WorkContext.StoreInfo.WeApp_Qrcode = model.WeApp_Qrcode ?? "";
                WorkContext.StoreInfo.WeService_Qrcode = model.WeService_Qrcode ?? "";
                WorkContext.StoreInfo.Email = model.Email ?? "";
                WorkContext.StoreInfo.WebSite = model.WebSite ?? "";
                WorkContext.StoreInfo.Mobile = model.Mobile ?? "";
                WorkContext.StoreInfo.Phone = model.Phone ?? "";
                WorkContext.StoreInfo.QQ = model.QQ ?? "";
                WorkContext.StoreInfo.WW = model.WW ?? "";
                WorkContext.StoreInfo.Theme = model.Theme;
                WorkContext.StoreInfo.Banner = model.Banner ?? "";
                WorkContext.StoreInfo.Announcement = model.Announcement ?? "";
                WorkContext.StoreInfo.Description = model.Description ?? "";
                WorkContext.StoreInfo.Address = model.Address ?? "";
                WorkContext.StoreInfo.Fax = model.Fax ?? "";
                WorkContext.StoreInfo.VideoSrc = model.VideoSrc ?? "";
                //RegionInfo regionInfo = Regions.GetRegionById(model.RegionId);
                //var location = QQMapApi.GetLocation(regionInfo.ProvinceName + regionInfo.CityName + regionInfo.Name +
                //                                  model.Address);
                //if (location != null && location.result != null && location.result.location != null)
                //    WorkContext.StoreInfo.Location = location.result.location.lat + "," +
                //                                     location.result.location.lng;
                WorkContext.StoreInfo.Location = model.Location ?? "22.543721,114.101514";
                WorkContext.StoreInfo.SupportPhone = model.SupportPhone ?? "";
                WorkContext.StoreInfo.SupportCompany = model.SupportCompany ?? "";
                if (WorkContext.StoreInfo.StorePid != model.StorePid)
                {
                    WorkContext.StoreInfo.StorePid = model.StorePid;
                    AdminStores.UpdateStorePId(WorkContext.StoreInfo.StoreId, model.StorePid);//修改平台ID
                }
                
                AdminStores.UpdateStore(WorkContext.StoreInfo);
                AddStoreAdminLog("修改店铺", "修改店铺");
                return PromptView(Url.Action("editstore"), "店铺修改成功");
            }

            LoadStore(model.RegionId);
            return View(model);
        }

        public ActionResult ClearStoreBanner(int storeId)
        {
            var storeInfo = Stores.GetStoreById(storeId);
            storeInfo.Banner = "";
            AdminStores.UpdateStore(storeInfo);
            return PromptView(Url.Action("editstore"), "清楚首页Logo成功");
        }

        private void LoadStore(int regionId)
        {
            List<SelectListItem> storeIndustryList = new List<SelectListItem>();
            storeIndustryList.Add(new SelectListItem() { Text = "选择店铺行业", Value = "-1" });
            foreach (StoreIndustryInfo storeIndustryInfo in AdminStoreIndustries.GetStoreIndustryList())
            {
                storeIndustryList.Add(new SelectListItem() { Text = storeIndustryInfo.Title, Value = storeIndustryInfo.StoreIid.ToString() });
            }
            ViewData["storeIndustryList"] = storeIndustryList;

            List<SelectListItem> themeList = new List<SelectListItem>();
            DirectoryInfo dir = new DirectoryInfo(IOHelper.GetMapPath("/themes"));
            foreach (DirectoryInfo themeDir in dir.GetDirectories())
            {
                themeList.Add(new SelectListItem() { Text = themeDir.Name, Value = themeDir.Name });
            }
            ViewData["themeList"] = themeList;

            RegionInfo regionInfo = Regions.GetRegionById(regionId);
            if (regionInfo != null)
            {
                ViewData["provinceId"] = regionInfo.ProvinceId;
                ViewData["cityId"] = regionInfo.CityId;
                ViewData["countyId"] = regionInfo.RegionId;
            }
            else
            {
                ViewData["provinceId"] = -1;
                ViewData["cityId"] = -1;
                ViewData["countyId"] = -1;
            }

            ViewData["allowImgType"] = BMAConfig.UploadConfig.UploadImgType.Replace(".", "");
            ViewData["maxImgSize"] = BMAConfig.UploadConfig.UploadImgSize;
        }





        /// <summary>
        /// 店铺分类列表
        /// </summary>
        public ActionResult StoreClassList()
        {
            StoreClassListModel model = new StoreClassListModel()
            {
                StoreClassList = AdminStores.GetStoreClassList(WorkContext.StoreId)
            };
            MallUtils.SetAdminRefererCookie(Url.Action("storeclasslist"));
            return View(model);
        }

        /// <summary>
        /// 添加店铺分类
        /// </summary>
        [HttpGet]
        public ViewResult AddStoreClass()
        {
            StoreClassModel model = new StoreClassModel();
            LoadStoreClass(WorkContext.StoreId);
            return View(model);
        }

        /// <summary>
        /// 添加店铺分类
        /// </summary>
        [HttpPost]
        public ActionResult AddStoreClass(StoreClassModel model)
        {
            if (Stores.GetStoreCidByStoreIdAndName(WorkContext.StoreId, model.StoreClassName) > 0)
                ModelState.AddModelError("StoreClassName", "名称已经存在");

            if (model.ParentId != 0 && Stores.GetStoreClassByStoreIdAndStoreCid(WorkContext.StoreId, model.ParentId) == null)
                ModelState.AddModelError("ParentId", "父分类不存在");

            if (ModelState.IsValid)
            {
                StoreClassInfo storeClassInfo = new StoreClassInfo()
                {
                    StoreId = WorkContext.StoreId,
                    DisplayOrder = model.DisplayOrder,
                    Name = model.StoreClassName,
                    ParentId = model.ParentId,
                    Logo = model.Logo ?? ""
                };

                AdminStores.CreateStoreClass(storeClassInfo);
                AddStoreAdminLog("添加店铺分类", "添加店铺分类,店铺分类为:" + model.StoreClassName);
                return PromptView("店铺分类添加成功");
            }

            LoadStoreClass(WorkContext.StoreId);
            return View(model);
        }

        /// <summary>
        /// 编辑店铺分类
        /// </summary>
        [HttpGet]
        public ActionResult EditStoreClass(int storeCid = -1)
        {
            StoreClassInfo storeClassInfo = AdminStores.GetStoreClassByStoreIdAndStoreCid(WorkContext.StoreId, storeCid);
            if (storeClassInfo == null)
                return PromptView("此店铺分类不存在");

            StoreClassModel model = new StoreClassModel();
            model.StoreClassName = storeClassInfo.Name;
            model.ParentId = storeClassInfo.ParentId;
            model.DisplayOrder = storeClassInfo.DisplayOrder;
            model.Logo = storeClassInfo.Logo;
            LoadStoreClass(WorkContext.StoreId);
            return View(model);
        }

        /// <summary>
        /// 编辑店铺分类
        /// </summary>
        [HttpPost]
        public ActionResult EditStoreClass(StoreClassModel model, int storeCid = -1)
        {
            StoreClassInfo storeClassInfo = AdminStores.GetStoreClassByStoreIdAndStoreCid(WorkContext.StoreId, storeCid);
            if (storeClassInfo == null)
                return PromptView("此店铺分类不存在");

            int storeCid2 = AdminStores.GetStoreCidByStoreIdAndName(WorkContext.StoreId, model.StoreClassName);
            if (storeCid2 > 0 && storeCid2 != storeCid)
                ModelState.AddModelError("StoreClassName", "名称已经存在");

            if (model.ParentId == storeClassInfo.StoreCid)
                ModelState.AddModelError("ParentId", "不能将自己作为父分类");

            if (model.ParentId != 0 && AdminStores.GetStoreClassByStoreIdAndStoreCid(WorkContext.StoreId, model.ParentId) == null)
                ModelState.AddModelError("ParentId", "父分类不存在");

            if (model.ParentId != 0 && AdminStores.GetChildStoreClassList(WorkContext.StoreId, storeCid, true).Exists(x => x.StoreCid == model.ParentId))
                ModelState.AddModelError("ParentId", "不能将分类调整到自己的子分类下");

            if (ModelState.IsValid)
            {
                int oldParentId = storeClassInfo.ParentId;

                storeClassInfo.ParentId = model.ParentId;
                storeClassInfo.Name = model.StoreClassName;
                storeClassInfo.DisplayOrder = model.DisplayOrder;
                storeClassInfo.Logo = model.Logo ?? "";
                AdminStores.UpdateStoreClass(storeClassInfo, oldParentId);
                AddStoreAdminLog("修改店铺分类", "修改店铺分类,店铺分类ID为:" + storeCid);
                return PromptView("商品修改成功");
            }

            LoadStoreClass(WorkContext.StoreId);
            return View(model);
        }

        /// <summary>
        /// 删除店铺分类
        /// </summary>
        public ActionResult DelStoreClass(int storeCid = -1)
        {
            int result = AdminStores.DeleteStoreClassByStoreIdAndStoreCid(WorkContext.StoreId, storeCid);
            if (result == -2)
                return PromptView("此店铺分类不存在");
            else if (result == -1)
                return PromptView("删除失败请先转移或删除此店铺分类下的店铺分类");
            else if (result == 0)
                return PromptView("删除失败请先转移或删除此店铺分类下的商品");
            AddStoreAdminLog("删除店铺分类", "删除店铺分类,店铺分类ID为:" + storeCid);
            return PromptView("店铺分类删除成功");
        }

        private void LoadStoreClass(int storeId)
        {
            ViewData["allowImgType"] = BMAConfig.UploadConfig.UploadImgType.Replace(".", "");
            ViewData["maxImgSize"] = BMAConfig.UploadConfig.UploadImgSize;
            ViewData["storeClassList"] = AdminStores.GetStoreClassList(storeId);
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
        }





        /// <summary>
        /// 店铺配送模板列表
        /// </summary>
        public ActionResult StoreShipTemplateList()
        {
            StoreShipTemplateListModel model = new StoreShipTemplateListModel()
            {
                StoreShipTemplateList = AdminStores.GetStoreShipTemplateList(WorkContext.StoreId)
            };

            MallUtils.SetAdminRefererCookie(Url.Action("storeshiptemplatelist"));
            return View(model);
        }

        /// <summary>
        /// 添加店铺配送模板
        /// </summary>
        [HttpGet]
        public ActionResult AddStoreShipTemplate()
        {
            AddStoreShipTemplateModel model = new AddStoreShipTemplateModel();
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            return View(model);
        }

        /// <summary>
        /// 添加店铺配送模板
        /// </summary>
        [HttpPost]
        public ActionResult AddStoreShipTemplate(AddStoreShipTemplateModel model)
        {
            if (ModelState.IsValid)
            {
                StoreShipTemplateInfo storeShipTemplateInfo = new StoreShipTemplateInfo()
                {
                    StoreId = WorkContext.StoreId,
                    Title = model.TemplateTitle,
                    Free = model.Free,
                    Type = model.Type,
                    FreeOrderAmount = model.FreeOrderAmount
                };

                int storeSTid = AdminStores.CreateStoreShipTemplate(storeShipTemplateInfo);
                if (storeSTid > 0)
                {
                    StoreShipFeeInfo storeShipFeeInfo = new StoreShipFeeInfo()
                    {
                        StoreSTid = storeSTid,
                        RegionId = -1,
                        StartValue = model.StartValue,
                        StartFee = model.StartFee,
                        AddValue = model.AddValue,
                        AddFee = model.AddFee
                    };
                    AdminStores.CreateStoreShipFee(storeShipFeeInfo);
                    AddStoreAdminLog("添加店铺配送模板", "添加店铺配送模板,店铺配送模板为:" + model.TemplateTitle);
                    return PromptView("店铺配送模板添加成功");
                }
                else
                {
                    return PromptView("店铺配送模板添加失败");
                }
            }
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            return View(model);
        }

        /// <summary>
        /// 编辑店铺配送模板
        /// </summary>
        [HttpGet]
        public ActionResult EditStoreShipTemplate(int storeSTid = -1)
        {
            StoreShipTemplateInfo storeShipTemplateInfo = AdminStores.GetStoreShipTemplateById(storeSTid);
            if (storeShipTemplateInfo == null)
                return PromptView("店铺配送模板不存在");
            if (storeShipTemplateInfo.StoreId != WorkContext.StoreId)
                return PromptView("不能操作其它店铺的配送模板");

            EditStoreShipTemplateModel model = new EditStoreShipTemplateModel();
            model.TemplateTitle = storeShipTemplateInfo.Title;
            model.Free = storeShipTemplateInfo.Free;
            model.Type = storeShipTemplateInfo.Type;
            model.FreeOrderAmount = storeShipTemplateInfo.FreeOrderAmount;
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            return View(model);
        }

        /// <summary>
        /// 编辑店铺配送模板
        /// </summary>
        [HttpPost]
        public ActionResult EditStoreShipTemplate(EditStoreShipTemplateModel model, int storeSTid = -1)
        {
            StoreShipTemplateInfo storeShipTemplateInfo = AdminStores.GetStoreShipTemplateById(storeSTid);
            if (storeShipTemplateInfo == null)
                return PromptView("店铺配送模板不存在");
            if (storeShipTemplateInfo.StoreId != WorkContext.StoreId)
                return PromptView("不能操作其它店铺的配送模板");

            if (ModelState.IsValid)
            {
                storeShipTemplateInfo.Title = model.TemplateTitle;
                storeShipTemplateInfo.Free = model.Free;
                storeShipTemplateInfo.Type = model.Type;
                storeShipTemplateInfo.FreeOrderAmount = model.FreeOrderAmount;
                AdminStores.UpdateStoreShipTemplate(storeShipTemplateInfo);
                AddStoreAdminLog("修改店铺配送模板", "修改店铺配送模板,店铺配送模板ID为:" + storeSTid);
                return PromptView("店铺配送模板修改成功");
            }

            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            return View(model);
        }

        /// <summary>
        /// 删除店铺配送模板
        /// </summary>
        public ActionResult DelStoreShipTemplate(int storeSTid = -1)
        {
            StoreShipTemplateInfo storeShipTemplateInfo = AdminStores.GetStoreShipTemplateById(storeSTid);
            if (storeShipTemplateInfo == null)
                return PromptView("店铺配送模板不存在");
            if (storeShipTemplateInfo.StoreId != WorkContext.StoreId)
                return PromptView("不能操作其它店铺的配送模板");

            int result = AdminStores.DeleteStoreShipTemplateById(storeSTid);
            if (result == -1)
                return PromptView("请先移除此模板下的商品");
            AddStoreAdminLog("删除店铺配送模板", "删除店铺配送模板,店铺配送模板ID为:" + storeSTid);
            return PromptView("店铺配送模板删除成功");
        }





        /// <summary>
        /// 店铺配送费用列表
        /// </summary>
        public ActionResult StoreShipFeeList(int storeSTid = -1)
        {
            StoreShipTemplateInfo storeShipTemplateInfo = AdminStores.GetStoreShipTemplateById(storeSTid);
            if (storeShipTemplateInfo == null)
                return PromptView("店铺配送模板不存在");
            if (storeShipTemplateInfo.StoreId != WorkContext.StoreId)
                return PromptView("不能操作其它店铺的配送模板");

            StoreShipFeeListModel model = new StoreShipFeeListModel()
            {
                StoreSTid = storeSTid,
                StoreShipFeeList = AdminStores.AdminGetStoreShipFeeList(storeSTid)
            };

            MallUtils.SetAdminRefererCookie(string.Format("{0}?storeSTid={1}", Url.Action("storeshipfeelist"), storeSTid));
            return View(model);
        }

        /// <summary>
        /// 添加店铺配送费用
        /// </summary>
        [HttpGet]
        public ActionResult AddStoreShipFee(int storeSTid = -1)
        {
            StoreShipTemplateInfo storeShipTemplateInfo = AdminStores.GetStoreShipTemplateById(storeSTid);
            if (storeShipTemplateInfo == null)
                return PromptView("店铺配送模板不存在");
            if (storeShipTemplateInfo.StoreId != WorkContext.StoreId)
                return PromptView("不能操作其它店铺的配送模板");

            StoreShipFeeModel model = new StoreShipFeeModel();
            LoadStoreShipFee(0);
            return View(model);
        }

        /// <summary>
        /// 添加店铺配送费用
        /// </summary>
        [HttpPost]
        public ActionResult AddStoreShipFee(StoreShipFeeModel model, int storeSTid = -1)
        {
            StoreShipTemplateInfo storeShipTemplateInfo = AdminStores.GetStoreShipTemplateById(storeSTid);
            if (storeShipTemplateInfo == null)
                return PromptView("店铺配送模板不存在");
            if (storeShipTemplateInfo.StoreId != WorkContext.StoreId)
                return PromptView("不能操作其它店铺的配送模板");

            if (ModelState.IsValid)
            {
                StoreShipFeeInfo storeShipFeeInfo = new StoreShipFeeInfo()
                {
                    StoreSTid = storeSTid,
                    RegionId = model.RegionId,
                    StartValue = model.StartValue,
                    StartFee = model.StartFee,
                    AddValue = model.AddValue,
                    AddFee = model.AddFee
                };
                AdminStores.CreateStoreShipFee(storeShipFeeInfo);
                AddStoreAdminLog("添加店铺配送费用", "添加店铺配送费用");
                return PromptView("店铺配送费用添加成功");
            }
            LoadStoreShipFee(model.RegionId);
            return View(model);
        }

        /// <summary>
        /// 编辑店铺配送费用
        /// </summary>
        [HttpGet]
        public ActionResult EditStoreShipFee(int recordId = -1)
        {
            StoreShipFeeInfo storeShipFeeInfo = AdminStores.GetStoreShipFeeById(recordId);
            if (storeShipFeeInfo == null)
                return PromptView("店铺配送费用不存在");
            StoreShipTemplateInfo storeShipTemplateInfo = AdminStores.GetStoreShipTemplateById(storeShipFeeInfo.StoreSTid);
            if (storeShipTemplateInfo == null)
                return PromptView("店铺配送模板不存在");
            if (storeShipTemplateInfo.StoreId != WorkContext.StoreId)
                return PromptView("不能操作其它店铺的配送模板");

            StoreShipFeeModel model = new StoreShipFeeModel();
            model.RegionId = storeShipFeeInfo.RegionId;
            model.StartValue = storeShipFeeInfo.StartValue;
            model.StartFee = storeShipFeeInfo.StartFee;
            model.AddValue = storeShipFeeInfo.AddValue;
            model.AddFee = storeShipFeeInfo.AddFee;

            LoadStoreShipFee(model.RegionId);
            return View(model);
        }

        /// <summary>
        /// 编辑店铺配送费用
        /// </summary>
        [HttpPost]
        public ActionResult EditStoreShipFee(StoreShipFeeModel model, int recordId = -1)
        {
            StoreShipFeeInfo storeShipFeeInfo = AdminStores.GetStoreShipFeeById(recordId);
            if (storeShipFeeInfo == null)
                return PromptView("店铺配送费用不存在");
            StoreShipTemplateInfo storeShipTemplateInfo = Stores.GetStoreShipTemplateById(storeShipFeeInfo.StoreSTid);
            if (storeShipTemplateInfo == null)
                return PromptView("店铺配送模板不存在");
            if (storeShipTemplateInfo.StoreId != WorkContext.StoreId)
                return PromptView("不能操作其它店铺的配送模板");

            if (ModelState.IsValid)
            {
                storeShipFeeInfo.RegionId = model.RegionId;
                storeShipFeeInfo.StartValue = model.StartValue;
                storeShipFeeInfo.StartFee = model.StartFee;
                storeShipFeeInfo.AddValue = model.AddValue;
                storeShipFeeInfo.AddFee = model.AddFee;

                AdminStores.UpdateStoreShipFee(storeShipFeeInfo);
                AddStoreAdminLog("修改店铺配送费用", "修改店铺配送费用,店铺配送费用ID为:" + recordId);
                return PromptView("店铺配送费用修改成功");
            }

            LoadStoreShipFee(model.RegionId);
            return View(model);
        }

        /// <summary>
        /// 删除店铺配送费用
        /// </summary>
        public ActionResult DelStoreShipFee(int recordId = -1)
        {
            StoreShipFeeInfo storeShipFeeInfo = AdminStores.GetStoreShipFeeById(recordId);
            if (storeShipFeeInfo == null)
                return PromptView("店铺配送费用不存在");
            StoreShipTemplateInfo storeShipTemplateInfo = AdminStores.GetStoreShipTemplateById(storeShipFeeInfo.StoreSTid);
            if (storeShipTemplateInfo == null)
                return PromptView("店铺配送模板不存在");
            if (storeShipTemplateInfo.StoreId != WorkContext.StoreId)
                return PromptView("不能操作其它店铺的配送模板");
            if (storeShipFeeInfo.RegionId == -1)
                return PromptView("默认店铺配送费用不能删除");

            AdminStores.DeleteStoreShipFeeById(recordId);
            AddStoreAdminLog("删除店铺配送费用", "删除店铺配送费用,店铺配送费用ID为:" + recordId);
            return PromptView("店铺配送费用删除成功");
        }

        private void LoadStoreShipFee(int regionId)
        {
            RegionInfo regionInfo = Regions.GetRegionById(regionId);
            if (regionInfo != null)
            {
                if (regionInfo.Layer == 1)
                {
                    ViewData["provinceId"] = regionInfo.ProvinceId;
                    ViewData["cityId"] = 0;
                }
                else
                {
                    ViewData["provinceId"] = regionInfo.ProvinceId;
                    ViewData["cityId"] = regionInfo.RegionId;
                }
            }
            else
            {
                ViewData["provinceId"] = 0;
                ViewData["cityId"] = 0;
            }

            ViewData["referer"] = MallUtils.GetMallAdminRefererCookie();
        }


        #region 微信设置

        public ActionResult StoreWxApp()
        {
            var data = StoreWxAppManager.GetStoreWxAppList(WorkContext.StoreId);
            var model = new StoreWxAppListModel
            {
                Result = data
            };
            MallUtils.SetAdminRefererCookie(Url.Action("StoreWxApp"));
            return View(model);
        }



        public ActionResult EditOrAddStoreWxApp(int wid = -1)
        {
            var model = new StoreWxAppModel();
            if (wid == -1)
            {
                model.StoreId = WorkContext.StoreId;
                model.Active = true;
                if (StoreWxAppManager.GetStoreWxAppList(WorkContext.StoreId).Count == 0)
                    model.IsDefault = true;
                return View("editstorewxapp", model);
            }
            var wxModel = StoreWxAppManager.Get(wid);
            model.MchId = wxModel.MchId;
            model.MchKey = wxModel.MchKey;
            model.StoreId = wxModel.StoreId;
            model.StoreWid = wxModel.StoreWid;
            model.WeAppId = wxModel.WeAppId;
            model.WeAppSecret = wxModel.WeAppSecret;
            model.DeliverSuccessTid = wxModel.DeliverSuccessTid;
            model.PaySuccessTid = wxModel.PaySuccessTid;
            model.AppointMentSuccessTid = wxModel.AppointMentSuccessTid;
            model.AppointMentDisposeSuccessTid = wxModel.AppointMentDisposeSuccessTid;
            model.SendMsgCallbackTid = wxModel.SendMsgCallbackTid;
            model.CertPath = wxModel.CertPath;
            model.IsDefault = wxModel.IsDefault;
            model.Active = wxModel.Active;
            model.PayType = wxModel.PayType;
            model.PsbcMchKey = wxModel.PsbcMchKey;
            model.PsbcMchId = wxModel.PsbcMchId;
            return View("editstorewxapp", model);



        }

        public ActionResult DeleteStoreWxapp(int wid)
        {
            var wxapp = StoreWxAppManager.Get(wid);
            if (wxapp.IsDefault)
                return PromptView(Url.Action("StoreWxApp"), "不能删除默认配置");
            var list = StoreWxAppManager.GetStoreWxAppList(WorkContext.StoreId);
            if (list.Count == 1) return PromptView(Url.Action("StoreWxApp"), "必须保留一个配置项");
            StoreWxAppManager.DeleteStoreWxApp(wid);
            return PromptView(Url.Action("StoreWxApp"), "删除成功");
        }

        [HttpPost]
        public ActionResult EditOrAddStoreWxApp(StoreWxAppModel model)
        {
            var wxModel = new StoreWxApp
            {
                MchId = model.MchId?.Trim() ?? "",
                MchKey = model.MchKey?.Trim() ?? "",
                StoreId = WorkContext.StoreId,
                StoreWid = model.StoreWid,
                WeAppId = model.WeAppId?.Trim() ?? "",
                WeAppSecret = model.WeAppSecret?.Trim() ?? "",
                DeliverSuccessTid = (model.DeliverSuccessTid ?? "").Trim(),
                PaySuccessTid = (model.PaySuccessTid ?? "").Trim(),
                AppointMentSuccessTid = (model.AppointMentSuccessTid ?? "").Trim(),
                AppointMentDisposeSuccessTid = (model.AppointMentDisposeSuccessTid ?? "").Trim(),
                SendMsgCallbackTid =model.SendMsgCallbackTid??"",
                CertPath = (model.CertPath ?? "").Trim(),
                IsDefault = model.IsDefault,
                Active = model.Active,
                PayType = model.PayType,
                PsbcMchKey = model.PsbcMchKey?.Trim() ?? "",
                PsbcMchId = model.PsbcMchId?.Trim() ?? ""
            };
            if (!string.IsNullOrEmpty(wxModel.WeAppId))
            {
                var auth = BrnMall.Manager.Manager.WeApp.AppAuthorizationManager.GetAppAuthorizationByAppId(wxModel.WeAppId);
                if (auth != null)
                    return PromptView("该小程序ID已经在第三方平台绑定，不能重新绑定");
            }


            StoreWxAppManager.UpdateOrAddStoreWxApp(wxModel);

            return PromptView(Url.Action("StoreWxApp"), "小程序配置成功");
        }
        #endregion

        #region 组件设置

        public ActionResult WidgetConfigList(string code, int cid = 0)
        {
            if (string.IsNullOrEmpty(code))
                return PromptView("组件Code不能为空");
            var widget = WidgetManager.GetWidget(WorkContext.StoreId, code);
            var uploadTips = string.Empty;
            if (widget == null)
            {
                var newWidget = new Widget { Code = code, IsActive = true, StoreId = WorkContext.StoreId };
                if (code == "index_banner")
                    newWidget.Name = "首页轮播";
                else if (code == "index_nav_icon")
                {
                    newWidget.Name = "首页按钮导航";
                }
                else if (code == "index_product")
                    newWidget.Name = "首页商品";
                WidgetManager.InsertWidget(newWidget);
                widget = WidgetManager.GetWidget(WorkContext.StoreId, code);
            }
            if (widget.Code == "index_banner")
            {
                uploadTips = "正方形建议800x800,长方形建议800x500";
            }
            else if (widget.Code == "index_nav_icon")
            {
                uploadTips = "建议100x100";
            }
            else if (widget.Code == "index_product")
                uploadTips = "建议500x70";
            var widgetModel = new WidgetModel
            {
                Code = widget.Code,
                Name = widget.Name,
                StoreId = widget.StoreId,
                WId = widget.WId,
                DisplayType = widget.DisplayType
            };
            var config = WidgetManager.GetConfigList(widget.WId).Select(t => new WidgetConfigModel
            {
                CId = t.CId,
                IsShow = t.IsShow,
                LinkType = t.LinkType,
                LinkValue = JsonConvert.DeserializeObject<LinkValue>(t.LinkValue),
                ShowName = t.ShowName,
                ShowImg = t.ShowImg,
                DisplayOrder = t.DisplayOrder,
                WId = t.WId,
                DisplayCount = t.DisplayCount,
                DisplayType = t.DisplayType,
                DisplayPosition = t.DisplayPosition
            }).ToList();

            //单个组件实体
            WidgetConfig configModel = cid < 1 ? new WidgetConfig() : WidgetManager.GetConfig(cid);

            var model = new WidgetConfigListModel
            {
                Config = config,
                Widget = widgetModel,
                StoreClassList = Stores.GetStoreClassList(WorkContext.StoreId),
                NewsTypeList = News.GetStoreNewsTypeList(WorkContext.StoreId),
                Code = code,
                PageInfos = PageInfoConfig.Pages,
                FunctionCodes= FunctionCodeInfoConfig.FunctionCodes,
                UploadImageTips = uploadTips,
                configModel = configModel
            };
            MallUtils.SetAdminRefererCookie($"{Url.Action("WidgetConfigList")}?code={code}");
            Load();
            if (code == "index_product")
                return View("IndexProductWidgetConfigList", model);
            if (code == "pc_index_product")
                return View("IndexProductWidgetConfigList", model);
            ViewData["code"] = code;
            return View(model);
        }

        public ActionResult ChangeWidgetConfigSort(int cid, int displayOrder = 0)
        {
            WidgetManager.SortConfig(cid, displayOrder);
            return Content("1");
        }
        [HttpPost]
        public ActionResult AddWidgetConfig(WidgetConfigPostModel model)
        {
            var con = new WidgetConfig
            {
                CId = model.CId,
                IsShow = model.IsShow,
                LinkType = model.LinkType,
                DisplayCount = model.DisplayCount,
                DisplayType = model.DisplayType
            };
            if (string.IsNullOrEmpty(model.LinkType))
                return PromptView("请选择链接类型");
            var linkValue = new LinkValue();
            switch (con.LinkType)
            {
                case "product":
                    if (string.IsNullOrEmpty(model.Pid))
                        return PromptView("链接到商品时，没有指定商品");
                    linkValue.Id = model.Pid;
                    linkValue.Name = model.ProductName;
                    linkValue.LinkType = con.LinkType;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                case "store_class":
                    if (string.IsNullOrEmpty(model.StoreClassId))
                        return PromptView("链接到店铺分类时，没有指定店铺分类");
                    linkValue.LinkType = con.LinkType;
                    linkValue.Id = model.StoreClassId;
                    linkValue.Name = Stores.GetStoreClassByStoreIdAndStoreCid(WorkContext.StoreId, TypeHelper.StringToInt(model.StoreClassId)).Name;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                case "news":
                    if (string.IsNullOrEmpty(model.NewsId))
                        return PromptView("链接到内容时，没有指定内容");
                    linkValue.LinkType = con.LinkType;
                    linkValue.Id = model.NewsId;
                    linkValue.Name = model.NewsName;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                case "news_type":
                    if (string.IsNullOrEmpty(model.NewsTypeId))
                        return PromptView("链接到内容分类时，没有指定内容分类");
                    linkValue.LinkType = con.LinkType;
                    linkValue.Id = model.NewsTypeId;
                    linkValue.Name = News.GetStoreNewsTypeById(WorkContext.StoreId, TypeHelper.StringToInt(model.NewsTypeId)).Name;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                case "page":
                    if (string.IsNullOrEmpty(model.PageInfoId))
                        return PromptView("链接到页面时，没有指定页面");
                    var pageInfo = PageInfoConfig.Get(model.PageInfoId);
                    linkValue.Id = pageInfo.Id;
                    linkValue.Url = pageInfo.Url;
                    linkValue.Name = pageInfo.Name;
                    linkValue.LinkType = con.LinkType;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                case "productattr":
                    if (string.IsNullOrEmpty(model.ProductAttr))
                        return PromptView("链接到商品特征时，没有指定商品特征");
                    linkValue.Id = model.ProductAttr;
                    var name = string.Empty;
                    if (linkValue.Id == "hot")
                        name = "热销";
                    else if (linkValue.Id == "new")
                        name = "新品";
                    else if (linkValue.Id == "best")
                        name = "精品";
                    linkValue.Name = name;
                    linkValue.LinkType = con.LinkType;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                case "h5page":
                    if (string.IsNullOrEmpty(model.H5Page))
                        return PromptView("链接到H5网页时，没有指定网页路径");

                    Uri url;
                    var t = Uri.TryCreate(model.H5Page, UriKind.Absolute, out url);
                    if (!t)
                        return PromptView("网页路径格式错误");
                    if (!url.Scheme.Equals("https"))
                        return PromptView("必须是https网页路径格式");
                    linkValue.Id = "0";
                    linkValue.Url = model.H5Page;
                    linkValue.Name = string.Empty;
                    linkValue.LinkType = con.LinkType;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                case "phonecall":
                    if (string.IsNullOrEmpty(model.PhoneNumber))
                        return PromptView("链接到一键拨号时，没有指定号码");
                    linkValue.Id = "0";
                    linkValue.Url = "";
                    linkValue.Name = model.PhoneNumber;
                    linkValue.LinkType = con.LinkType;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                case "weappfunc":
                    if (string.IsNullOrEmpty(model.FunctionCode))
                        return PromptView("链接到扫码时，没有指定二维码");
                    linkValue.Id = "0";
                    linkValue.Url = "";
                    linkValue.Name = model.FunctionCode;
                    linkValue.LinkType = con.LinkType;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                default:
                    linkValue.Id = string.Empty;
                    linkValue.Name = string.Empty;
                    linkValue.LinkType = string.Empty;
                    break;
            }

            con.ShowImg = model.ShowImg ?? "";
            con.ShowName = model.ShowName ?? "";
            con.DisplayOrder = model.DisplayOrder;
            con.WId = model.WId;

            var widget = WidgetManager.GetWidget(model.WId);
            widget.DisplayType = model.WidgetDisplayType?1:0;
            WidgetManager.UpdateWidget(widget);
            if (con.CId > 0)
            {
                WidgetManager.UpdateConfig(con);    //修改
                return PromptView(Url.Action("WidgetConfigList", "Store", new { code = model.Code }), "修改成功");
            }
            else
            {
                WidgetManager.InsertConfig(con);    //添加
                return PromptView(Url.Action("WidgetConfigList", "Store", new { code = model.Code }), "添加成功");
            }
        }

        public ActionResult DeleteWidgetConfig(int cid)
        {
            WidgetManager.DeleteConfig(cid);
            return Content("1");
        }

        #region 图片组件
        public ActionResult IndexPictureWidgetConfigList(string code= "")
        {
            //2018-03-07 注释
            //var widget = WidgetManager.GetWidget(WorkContext.StoreId, "index_pic_area");
            code = code == "" ? "index_pic_area" : code;
            var widget = WidgetManager.GetWidget(WorkContext.StoreId, code);
            if (widget == null)
            {
                widget = new Widget
                {
                    //Code = "index_pic_area",
                    Code = code,
                    IsActive = true,
                    StoreId = WorkContext.StoreId,
                    Name = "首页图片组件"
                };
                WidgetManager.InsertWidget(widget);
            }
            var widgetModel = new WidgetModel
            {
                Code = widget.Code,
                Name = widget.Name,
                StoreId = widget.StoreId,
                WId = widget.WId
            };
            var config = WidgetManager.GetConfigList(widget.WId).Select(t => new WidgetConfigModel
            {
                CId = t.CId,
                IsShow = t.IsShow,
                ShowName = t.ShowName,
                ShowImg = t.ShowImg,
                DisplayOrder = t.DisplayOrder,
                WId = t.WId,
                DisplayType = t.DisplayType,
                DisplayPosition = t.DisplayPosition
            }).ToList();

            var model = new WidgetConfigListModel
            {
                Config = config,
                Widget = widgetModel,
                Code = code
                //Code = "index_pic_area"
            };


            Load();
            return View(model);
        }
        [HttpPost]
        public ActionResult AddIndexPictureWidgetConfig(IndexPictureWidgetConfigPostModel model, string code = "")
        {
            var con = new WidgetConfig
            {
                IsShow = model.IsShow,
                DisplayType = model.DisplayType,
                ShowName = model.ShowName,
                DisplayOrder = model.DisplayOrder,
                DisplayPosition = model.DisplayPosition,
                WId = model.WId
            };
            WidgetManager.InsertConfig(con);
            var wiget = WidgetManager.GetWidget(con.WId);

            return PromptView(Url.Action("IndexPictureWidgetConfigList", "Store", new { code = code }), "新增成功");
        }
        public ActionResult EditIndexPictureCustomerFeatures(int cid)
        {
            if (cid < 1) return PromptView("参数错误");
            var t = WidgetManager.GetConfig(cid);
            var model = new EditIndexPictureWidgetCustomerFeaturesModel
            {
                WidgetConfig = new WidgetConfigModel
                {
                    CId = t.CId,
                    IsShow = t.IsShow,
                    ShowName = t.ShowName,
                    DisplayOrder = t.DisplayOrder,
                    WId = t.WId,
                    DisplayType = t.DisplayType,
                    DisplayPosition = t.DisplayPosition
                },

                StoreClassList = Stores.GetStoreClassList(WorkContext.StoreId),
                NewsTypeList = News.GetStoreNewsTypeList(WorkContext.StoreId),
                PageInfos = PageInfoConfig.Pages,
                FunctionCodes = FunctionCodeInfoConfig.FunctionCodes,

            };
            if (!string.IsNullOrEmpty(t.CustomerFeatures))
                model.CustomerFeatures = JsonConvert.DeserializeObject<IList<LinkValue>>(t.CustomerFeatures);
            if (t.DisplayType > 10 && t.DisplayType < 20)
                model.LinkArea = new[] { "A", "B", "C", "D", "E", "F" }.Take(t.DisplayType - 10).ToArray();
            if (t.DisplayType == 16||t.DisplayType==17) //轮播
                model.LinkArea = new[] {"A"};
            if (t.DisplayType == 11)
            {
                model.UploadTips.Add("长宽比例2:1，建议最低像素480x240");
            }
            else if (t.DisplayType == 12 || t.DisplayType == 14)
            {
                model.UploadTips.Add("长宽比例1:1，建议最低像素240x240");
            }
            else if (t.DisplayType == 13)
            {
                model.UploadTips.Add("图片区域A：长宽比例1:1，建议最低像素240x240");
                model.UploadTips.Add("图片区域B,C：长宽比例2:1，建议最低像素240x120");
            }
            else if (t.DisplayType == 15)
            {
                model.UploadTips.Add("图片区域A：长宽比例1:2，建议最低像素120x240");
                model.UploadTips.Add("图片区域B,C,D,E：长宽比例1:1，建议最低像素120x120");
            }
            else if (t.DisplayType == 16)
            {
                model.UploadTips.Add("图片尺寸建议800x500");
            }else if (t.DisplayType == 17)
            {
                model.UploadTips.Add("图片长宽比例1:1，尺寸建议最小240x240");
            }
            MallUtils.SetAdminRefererCookie(Url.Action("IndexPictureWidgetConfigList"));
            Load();
            return View(model);
        }
        [HttpPost]
        public ActionResult AddIndexPictureCustomerFeatures(EditIndexPictureWidgetCustomerFeaturesPostModel model)
        {

            if (model.CId < 1) return PromptView("参数错误");
            MallUtils.SetAdminRefererCookie(Url.Action("EditIndexPictureCustomerFeatures", "Store", new { cid = model.CId }));
            var t = WidgetManager.GetConfig(model.CId);
            var pics = JsonConvert.DeserializeObject<IList<LinkValue>>(t.CustomerFeatures) ?? new List<LinkValue>();
            var find = pics.Where(x => x.LinkArea == model.LinkArea).ToList();
            if (find.Count>0&&t.DisplayType!=16&&t.DisplayType!=17)
                return PromptView($"区域{model.LinkArea}已经定义了图片");
            var linkValue = new LinkValue
            {
                LinkType = model.LinkType,
                LinkArea = model.LinkArea,
                ShowImg = model.ShowImg
            };
            switch (linkValue.LinkType)
            {
                case "product":
                    if (string.IsNullOrEmpty(model.Pid))
                        return PromptView("请选择商品");
                    linkValue.Id = model.Pid;
                    linkValue.Name = model.ProductName;
                    break;
                case "store_class":
                    if (string.IsNullOrEmpty(model.StoreClassId))
                        return PromptView("请选择店铺分类");
                    linkValue.Id = model.StoreClassId;
                    linkValue.Name = Stores.GetStoreClassByStoreIdAndStoreCid(WorkContext.StoreId, TypeHelper.StringToInt(model.StoreClassId)).Name;
                    break;
                case "news":
                    if (string.IsNullOrEmpty(model.NewsId))
                        return PromptView("请选择内容");
                    linkValue.Id = model.NewsId;
                    linkValue.Name = model.NewsName;
                    break;
                case "news_type":
                    if (string.IsNullOrEmpty(model.NewsTypeId))
                        return PromptView("请选择内容分类");
                    linkValue.Id = model.NewsTypeId;
                    linkValue.Name = News.GetStoreNewsTypeById(WorkContext.StoreId, TypeHelper.StringToInt(model.NewsTypeId)).Name;
                    break;
                case "page":
                    if (string.IsNullOrEmpty(model.PageInfoId))
                        return PromptView("请选择页面");
                    var pageInfo = PageInfoConfig.Get(model.PageInfoId);
                    linkValue.Id = pageInfo.Id;
                    linkValue.Url = pageInfo.Url;
                    linkValue.Name = pageInfo.Name;
                    break;
                case "h5page":
                    if (string.IsNullOrEmpty(model.H5Page))
                        return PromptView("链接到H5网页时，没有指定网页路径");

                    Uri url;
                    var h5 = Uri.TryCreate(model.H5Page, UriKind.Absolute, out url);
                    if (!h5)
                        return PromptView("网页路径格式错误");
                    if (!url.Scheme.Equals("https"))
                        return PromptView("必须是https网页路径格式");
                    linkValue.Id = "0";
                    linkValue.Url = model.H5Page;
                    linkValue.Name = string.Empty;
                    break;
                case "phonecall":
                    if (string.IsNullOrEmpty(model.PhoneNumber))
                        return PromptView("链接到一键拨号时，没有指定号码");
                    linkValue.Id = "0";
                    linkValue.Url = "";
                    linkValue.Name = model.PhoneNumber;

                    break;
                case "weappfunc":
                    if (string.IsNullOrEmpty(model.FunctionCode))
                        return PromptView("链接到扫码时，没有指定二维码");
                    linkValue.Id = "0";
                    linkValue.Url = "";
                    linkValue.Name = model.FunctionCode;
                    break;
                default:
                    linkValue.Id = string.Empty;
                    linkValue.Name = string.Empty;
                    linkValue.LinkType = string.Empty;
                    break;
            }
            if (string.IsNullOrEmpty(linkValue.Id))
                return PromptView("选择链接错误");
            pics.Add(linkValue);
            var features = JsonConvert.SerializeObject(pics);
            WidgetManager.UpdateWidgetCustomerFeatures(model.CId, features);

            return PromptView("新增成功");
        }

        public ActionResult DeleteIndexPictureCustomerFeatures(int cid, int itemIndex)
        {
            if (cid < 1) return Content("0");
            var t = WidgetManager.GetConfig(cid);
            var pics = JsonConvert.DeserializeObject<IList<LinkValue>>(t.CustomerFeatures);
            var find = pics.SingleOrDefault(x => x == pics[itemIndex]);
            if (find != null)
                pics = pics.Where(x => x != pics[itemIndex]).ToList();
            t.CustomerFeatures = JsonConvert.SerializeObject(pics);
            WidgetManager.UpdateWidgetCustomerFeatures(cid, t.CustomerFeatures);
            return Content("1");
        }
        #endregion

        #region 内容组件(PC网站用到)
        [HttpPost]
        public ActionResult AddNewsWidgetConfig(WidgetConfigPostModel model)
        {
            var con = new WidgetConfig
            {
                CId = model.CId,
                IsShow = model.IsShow,
                LinkType = model.LinkType,
                DisplayCount = model.DisplayCount,
                DisplayType = model.DisplayType
            };
            if (string.IsNullOrEmpty(model.LinkType))
                return PromptView("请选择链接类型");
            var linkValue = new LinkValue();
            switch (con.LinkType)
            {
                case "product":
                    if (string.IsNullOrEmpty(model.Pid))
                        return PromptView("链接到商品时，没有指定商品");
                    linkValue.Id = model.Pid;
                    linkValue.Name = model.ProductName;
                    linkValue.LinkType = con.LinkType;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                case "store_class":
                    if (string.IsNullOrEmpty(model.StoreClassId))
                        return PromptView("链接到店铺分类时，没有指定店铺分类");
                    linkValue.LinkType = con.LinkType;
                    linkValue.Id = model.StoreClassId;
                    linkValue.Name = Stores.GetStoreClassByStoreIdAndStoreCid(WorkContext.StoreId, TypeHelper.StringToInt(model.StoreClassId)).Name;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                case "news":
                    if (string.IsNullOrEmpty(model.NewsId))
                        return PromptView("链接到内容时，没有指定内容");
                    linkValue.LinkType = con.LinkType;
                    linkValue.Id = model.NewsId;
                    linkValue.Name = model.NewsName;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                case "news_type":
                    if (string.IsNullOrEmpty(model.NewsTypeId))
                        return PromptView("链接到内容分类时，没有指定内容分类");
                    linkValue.LinkType = con.LinkType;
                    linkValue.Id = model.NewsTypeId;
                    linkValue.Name = News.GetStoreNewsTypeById(WorkContext.StoreId, TypeHelper.StringToInt(model.NewsTypeId)).Name;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                case "page":
                    if (string.IsNullOrEmpty(model.PageInfoId))
                        return PromptView("链接到页面时，没有指定页面");
                    var pageInfo = PageInfoConfig.Get(model.PageInfoId);
                    linkValue.Id = pageInfo.Id;
                    linkValue.Url = pageInfo.Url;
                    linkValue.Name = pageInfo.Name;
                    linkValue.LinkType = con.LinkType;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                case "productattr":
                    if (string.IsNullOrEmpty(model.ProductAttr))
                        return PromptView("链接到商品特征时，没有指定商品特征");
                    linkValue.Id = model.ProductAttr;
                    var name = string.Empty;
                    if (linkValue.Id == "hot")
                        name = "热销";
                    else if (linkValue.Id == "new")
                        name = "新品";
                    else if (linkValue.Id == "best")
                        name = "精品";
                    linkValue.Name = name;
                    linkValue.LinkType = con.LinkType;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                case "h5page":
                    if (string.IsNullOrEmpty(model.H5Page))
                        return PromptView("链接到H5网页时，没有指定网页路径");

                    Uri url;
                    var t = Uri.TryCreate(model.H5Page, UriKind.Absolute, out url);
                    if (!t)
                        return PromptView("网页路径格式错误");
                    if (!url.Scheme.Equals("https"))
                        return PromptView("必须是https网页路径格式");
                    linkValue.Id = "0";
                    linkValue.Url = model.H5Page;
                    linkValue.Name = string.Empty;
                    linkValue.LinkType = con.LinkType;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                case "phonecall":
                    if (string.IsNullOrEmpty(model.PhoneNumber))
                        return PromptView("链接到一键拨号时，没有指定号码");
                    linkValue.Id = "0";
                    linkValue.Url = "";
                    linkValue.Name = model.PhoneNumber;
                    linkValue.LinkType = con.LinkType;
                    con.LinkValue = JsonConvert.SerializeObject(linkValue);
                    break;
                default:
                    linkValue.Id = string.Empty;
                    linkValue.Name = string.Empty;
                    linkValue.LinkType = string.Empty;
                    break;
            }

            con.ShowImg = model.ShowImg ?? "";
            con.ShowName = model.ShowName ?? "";
            con.DisplayOrder = model.DisplayOrder;
            con.WId = model.WId;

            if (con.CId > 0)
            {
                WidgetManager.UpdateConfig(con);    //修改
                return PromptView(Url.Action("NewsWidGetConfigList", "Store", new { code = model.Code }), "修改成功");
            }
            else
            {
                WidgetManager.InsertConfig(con);    //添加
                return PromptView(Url.Action("NewsWidGetConfigList", "Store", new { code = model.Code }), "添加成功");
            }
        }

        #endregion

        #endregion

        #region 门店
        [HttpGet]
        public ActionResult AddBranch()
        {
            ViewData["allowImgType"] = BMAConfig.UploadConfig.UploadImgType.Replace(".", "");
            ViewData["maxImgSize"] = BMAConfig.UploadConfig.UploadImgSize;
            MallUtils.SetAdminRefererCookie(Url.Action("AddBranch"));
            return View(new BranchModel());
        }

        /// <summary>
        /// 添加门店
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddBranch(BranchModel info)
        {
            if (string.IsNullOrEmpty(info.Name))
                return PromptView("请填写门店名称");
            if (string.IsNullOrEmpty(info.Phone))
                return PromptView("请填写电话");
            if (string.IsNullOrEmpty(info.Location))
                return PromptView("请填写坐标");
            if (string.IsNullOrEmpty(info.Logo))
                return PromptView("请上传门店LOGO");

            var model = GetBranchInfo(info);

            if (BranchManager.Add(model))
            {
                MallUtils.SetAdminRefererCookie(Url.Action("BranchList"));
                AddStoreAdminLog("添加门店", "添加门店,名称为:" + model.Name);
                return PromptView("门店添加成功");
            }
            return PromptView("门店添加失败");
        }

        /// <summary>
        /// 删除门店
        /// </summary>
        /// <param name="bid"></param>
        /// <returns></returns>
        public ActionResult DeleteBranch(int bid)
        {
            var model = BranchManager.Get(bid);
            if (model != null)
            {
                if (model.StoreId != WorkContext.StoreId)
                    return PromptView("只能删除自己的门店");

                BranchManager.Delete(bid, model.StoreId);
                AddStoreAdminLog("删除门店", "删除门店,名称为:" + model.Name);
            }
            MallUtils.SetAdminRefererCookie(Url.Action("BranchList"));
            return PromptView("门店删除成功");
        }


        /// <summary>
        /// 修改门店
        /// </summary>
        [HttpGet]
        public ActionResult EditBranch(int bid)
        {
            var info = BranchManager.Get(bid);
            if (info == null)
                return PromptView("门店不存在");
            if (info.StoreId != WorkContext.StoreId)
                return PromptView("只能修改自己的门店");

            var model = GetBranchModel(info);
            MallUtils.SetAdminRefererCookie(Url.Action("EditBranch", new { bid = bid }));
            return View(model);
        }

        /// <summary>
        /// 修改门店
        /// </summary>
        [HttpPost]
        public ActionResult EditBranch(BranchModel info)
        {
            if (string.IsNullOrEmpty(info.Name))
                return PromptView("请填写门店名称");
            if (string.IsNullOrEmpty(info.Phone))
                return PromptView("请填写电话");
            if (string.IsNullOrEmpty(info.Location))
                return PromptView("请填写坐标");
            if (string.IsNullOrEmpty(info.Logo))
                return PromptView("请上传门店LOGO");

            var model = GetBranchInfo(info);

            if (BranchManager.Update(model))
            {
                AddStoreAdminLog("修改门店", "修改门店,修改后名称为:" + model.Name);
                MallUtils.SetAdminRefererCookie(Url.Action("BranchList"));
                return PromptView("门店修改成功");
            }
            return PromptView("门店修改失败");
        }

        /// <summary>
        /// 门店图片列表
        /// </summary>
        /// <param name="bid"></param>
        /// <returns></returns>
        public ActionResult BranchImgs(int bid)
        {
            var info = BranchManager.Get(bid);
            if (info == null)
                return PromptView("门店不存在");
            if (info.StoreId != WorkContext.StoreId)
                return PromptView("只能修改自己的门店");

            var model = GetBranchModel(info);
            MallUtils.SetAdminRefererCookie(Url.Action("BranchImgs", new { bid = bid }));
            return View(model);
        }

        /// <summary>
        /// 修改门店图片
        /// </summary>
        /// <param name="bid"></param>
        /// <param name="imgs">门店图片，多个用逗号隔开</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EidtBranchImg(int bid, string imgs)
        {
            BranchManager.UpdateImgs(bid, imgs);
            return PromptView("门店图片保存成功");
        }

        /// <summary>
        /// 店铺门店列表
        /// </summary>
        public ActionResult BranchList(int pageNumber = 1, int pageSize = 15)
        {
            var dbList = BranchManager.GetListPage(WorkContext.StoreId, pageNumber, pageSize);
            var model = new BranchListModel()
            {
                Result = dbList.Items,
                PageModel = new PageModel(pageSize, pageNumber, (int)dbList.TotalItems),
            };
            MallUtils.SetAdminRefererCookie(Url.Action("BranchList"));
            return View(model);
        }

        BranchInfo GetBranchInfo(BranchModel info)
        {
            var model = new BranchInfo()
            {
                Bid = info.Bid,
                StoreId = WorkContext.StoreId,
                CreateTime = DateTime.Now,
                Address = info.Address,
                Name = info.Name,
                Phone = info.Phone,
                Logo = info.Logo,
                Location = info.Location,
                DisplayOrder = info.DisplayOrder,
                Description = info.Description,
                BusinessDesc = info.BusinessDesc,
                BusinessHours = info.BusinessHours,
                Imgs = info.Imgs
            };
            return model;
        }

        BranchModel GetBranchModel(BranchInfo info)
        {
            var model = new BranchModel()
            {
                Bid = info.Bid,
                Name = info.Name,
                Phone = info.Phone,
                StoreId = info.StoreId,
                Address = info.Address,
                CreateTime = info.CreateTime,
                Description = info.Description,
                DisplayOrder = info.DisplayOrder,
                Location = info.Location,
                Logo = info.Logo,
                BusinessDesc = info.BusinessDesc,
                BusinessHours = info.BusinessHours,
                Imgs = info.Imgs
            };
            return model;
        }
        #endregion

        private void Load()
        {
            ViewData["allowImgType"] = BMAConfig.UploadConfig.UploadImgType.Replace(".", "");
            ViewData["maxImgSize"] = BMAConfig.UploadConfig.UploadImgSize;
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
        }
    }
}
